package com.xinzhi.seckill.controller;

import com.xinzhi.seckill.pojo.User;
import com.xinzhi.seckill.service.IGoodsService;
import com.xinzhi.seckill.service.IUserService;
import com.xinzhi.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;



import java.util.Date;

/**
 * 跳转到商品列表页面
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;

    @RequestMapping("/toList")
    //HttpSession 通过session获取用户信息和cookie
    //Model 做页面跳转可能商品页面上需要展示对应信息，跳转时通过Model传
    //ticket 通过cookie的值  @CookieValue拿到service中设置的cookiename
//    public String toList(HttpSession session, Model model,@CookieValue("userTicket") String ticket){
    public String toList(Model model,User user){
//        //判断ticket是否为空
//        if (StringUtils.isEmpty(ticket)){
//            return "login";
//        }
//
//        //根据（ticket）去session中获取用户信息
////        User user = (User) session.getAttribute(ticket);
//
//        //使用redis存储用户信息
//        User user = userService.getUserByCookie(ticket, response, request);
//        if (null == user){
//            return "login";
//        }
        //如果都没问题；addAttribute加个属性，将用户对象传到前端页面中，进行相应跳转
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        return "goodsList";
    }

    /**
     * 跳转商品详情页
     * @param goodsId
     * @return
     */
    @RequestMapping("/toDetail/{goodsId}")
    public String toDetail(Model model,User user,@PathVariable Long goodsId){
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        //秒杀开始时间
        Date startDate = goodsVo.getStockDate();
        //秒杀结束时间
        Date endDate = goodsVo.getEndDate();
        //当前时间
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        //秒杀还未开始
        if (nowDate.before(startDate)){
            remainSeconds = ((int) ((startDate.getTime() - nowDate.getTime()) / 1000));
            //秒杀已结束
        }else if (nowDate.after(endDate)){
            secKillStatus = 2;
            remainSeconds = -1;
        }else {
            //秒杀中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("secKillStatus",secKillStatus);
        model.addAttribute("goods",goodsVo);

        return "goodsDetail";
    }
}
